// 创建浮动窗口
const floatingWindow = document.createElement("div");
floatingWindow.id = "dev-helper-floating";
document.body.appendChild(floatingWindow);

// 初始化资源列表
let resources = [];

// 接收后台消息
chrome.runtime.onMessage.addListener((message) => {
  if (message.type === "resource-loaded") {
    resources.push(message.data);
    console.log("Received resource-loaded message:", message.data);
    updateFloatingWindow();
  }
});

// 更新浮动窗口内容
function updateFloatingWindow() {
  floatingWindow.innerHTML = `
    <div class="header">
      <h3>已加载资源 (${resources.length})</h3>
    </div>
    <div class="resource-list">
      ${resources
        .map(
          (r) => `
        <div class="resource-item">
          <div class="name">
          <div>${r.name}</div>
          <div> <mark>${r.matchContent}</mark></div>
          </div>
          
          <span class="url">${r.url}</span>
        </div>
      `
        )
        .join("")}
    </div>
  `;
}

// 窗口样式初始化
Object.assign(floatingWindow.style, {
  position: "fixed",
  bottom: "20px",
  right: "20px",
  width: "400px",
  maxHeight: "80vh",
  backgroundColor: "#fff",
  boxShadow: "0 2px 10px rgba(0,0,0,0.2)",
  borderRadius: "8px",
  overflow: "hidden",
  zIndex: "9999",
});

// 使用MutationObserver自动更新位置
const observer = new MutationObserver(() => {
  const viewportWidth = Math.max(
    document.documentElement.clientWidth || 0,
    window.innerWidth || 0
  );
  floatingWindow.style.right = `${Math.max(
    20,
    viewportWidth - document.documentElement.offsetWidth + 20
  )}px`;
});
observer.observe(document.documentElement, { attributes: true });
